package com.itheima.web.filters;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.itheima.domain.system.User;
import com.itheima.service.system.UserService;
import com.itheima.service.system.impl.UserServiceImpl;
import com.itheima.utils.CookieUtils;

/**
 * 自动登录过滤器
 */
@WebFilter("/*")
public class AutoLoginFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;

        //优化: 用户已经登录,就不要自动登录
        Object uu = request.getSession().getAttribute("user");
        if (uu != null) {
            //用户已经登录
            chain.doFilter(request, response);
            return;
        }

        String autoLoginCookie = CookieUtils.getCookieValue(request, "autoLoginCookie");
        //2. 判断cookie是否存在
        if (autoLoginCookie == null) {
            //2.1 若无: 放行
            chain.doFilter(request, response);
            return;
        }

        //2.2 若有: 获取cookie 中用户名和密码

        String username = autoLoginCookie.split("@")[0];
        String password = autoLoginCookie.split("@")[1];
        username = URLDecoder.decode(username, "utf-8");
        //3. 调用service查询用户,判断用户是否存在(用户有可能修改了密码)
        UserService userService = new UserServiceImpl();
        User user = userService.login(username, password);

        if (user == null) {
            //3.1 若无: 放行
            chain.doFilter(request, response);
            return;
        }
        request.getSession().setAttribute("user", user);
        request.getRequestDispatcher("/pages/main.jsp").forward(request, response);
        chain.doFilter(request, response);

    }

    /**
     * 根据名称查询需要的cookie对象
     *
     * @param cookies
     * @param cookieName
     * @return
     */
    private Cookie getCookieByName(Cookie[] cookies, String cookieName) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equals(cookie.getName())) {
                    //找到指定cookie
                    return cookie;
                }
            }
        }
        return null;
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void destroy() {

    }

}
